/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cageballtv;

import cageballcommon.messages.InitTeam;
import cageballcommon.exceptions.CageballIOException;
import cageballcommon.exceptions.CageballParseException;
import cageballcommon.io.interfaces.CageballReader;
import cageballcommon.messages.State;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author kanonas
 */
public class StateReceiver implements Runnable {

    private Properties properties = null;
    private LinkedBlockingQueue<State> queue;
    private InitTeam team1;
    private InitTeam team2;
    private Boolean ready;
    private int bufferSize;
    private CageballReader reader;

    public StateReceiver(CageballReader io, int bufferSize) {
        this.reader = io;
        this.bufferSize = bufferSize;

        queue = new LinkedBlockingQueue<State>();
        ready = false;
    }

    public Properties getProperties() {
        return properties;
    }

    public InitTeam getTeam1() {
        return team1;
    }

    public InitTeam getTeam2() {
        return team2;
    }

    public State getNextState() throws InterruptedException {
        return queue.take();
    }

    public void init() throws InterruptedException {
        synchronized (this) {
            if (!ready) {
                this.wait();
            }
        }
    }

    public void run() {
        try {
            while (true) {
                properties = reader.readProperties();

                team1 = reader.readInitTeam();
                team2 = reader.readInitTeam();

                State state;
                for (int i = 0; i < bufferSize; i++) {

                    state = reader.readState();
                    queue.add(state);
                    if (state.getInfo() != null) {
                        if (state.getInfo().getWinner() != null) {
                            ready = false;
                            break;
                        }
                    }
                }

                synchronized (this) {
                    ready = true;
                    this.notifyAll();
                }

                while (true) {
                    state = reader.readState();

                    queue.add(state);

                    if(state.getInfo() != null){
                        if(state.getInfo().getWinner() != null){
                            ready = false;
                            break;
                        }
                    }
                }
            }
        } catch (CageballParseException ex) {
            System.out.println(ex.getMessage());
        } catch (CageballIOException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
